package com.example.blog.interceptor;

import com.example.blog.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
//拦截器
public class LoginInterceptor implements HandlerInterceptor {
    //在目标方法执行前进行校验
    //简写pre就会出来方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //校验token是否正确
        //在前端ajaxSend(发送ajax请求)从localStorage里面获取token,见common.js
        String token=request.getHeader("user_header_token");
        log.info("从header中获取token,token:{}",token);
        //校验token是否存在
        Claims claims=JwtUtil.parseToken(token);
        //token不合法
        if(claims==null){
            response.setStatus(401);
            return false;
        }
        //TODO 也可以做的细一点
        //比如校验ID和name是否匹配,是否存在
//        claims.get("name")
        return true;
    }
}
